package dao

import (
	"ginApi/comm"
	"ginApi/db"
	"ginApi/model"
)

type UserDao struct{}

func NewUserDao() *UserDao {
	return &UserDao{}
}

func (d *UserDao) FindById(id int64) *model.User {
	var user model.User
	db.DB.First(&user, id)

	if user.ID <= 0 {
		return nil
	}

	return &user
}

func (d *UserDao) CheckExist(username string) bool {
	var user model.User
	db.DB.Where("username = ?", username).First(&user)

	if user.ID <= 0 {
		return false
	}

	return true
}

func (d *UserDao) InsertUser(username, password string) *model.User {
	user := &model.User{Username: username, Password: comm.CreateSign(password)}

	if err := db.DB.Create(user).Error; err != nil {
		return nil
	}

	return user
}

func (d *UserDao) CheckAccount(username, password string) *model.User {
	var user model.User
	db.DB.Where("username = ? and password = ?", username, comm.CreateSign(password)).First(&user)

	if user.ID <= 0 {
		return nil
	}

	return &user
}
